package com.example.deepai;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import okhttp3.*;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@SpringBootTest
public class DeepSeekApiTest {

    @Value("${deepseek.api.key}")
    private String apiKey;

    @Value("${deepseek.api.url}")
    private String apiUrl;

    @Test
    public void testDeepSeekApi() throws IOException {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .build();

        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode requestBody = objectMapper.createObjectNode();
        requestBody.put("model", "deepseek-chat");
        requestBody.put("temperature", 0.7);

        ArrayNode messagesArray = requestBody.putArray("messages");
        ObjectNode messageNode = messagesArray.addObject();
        messageNode.put("role", "user");
        messageNode.put("content", "Hello, how are you?");

        String requestJson = requestBody.toString();
        System.out.println("Request: " + requestJson);

        // Updated to use non-deprecated method
        RequestBody body = RequestBody.create(requestJson, MediaType.parse("application/json"));

        Request request = new Request.Builder()
                .url(apiUrl)
                .post(body)
                .addHeader("Authorization", "Bearer " + apiKey)
                .addHeader("Content-Type", "application/json")
                .build();

        try (Response response = client.newCall(request).execute()) {
            String responseBody = response.body().string();
            System.out.println("Response code: " + response.code());
            System.out.println("Response body: " + responseBody);
            
            if (response.isSuccessful()) {
                JsonNode responseJson = objectMapper.readTree(responseBody);
                String content = responseJson.path("choices").path(0).path("message").path("content").asText();
                System.out.println("AI response: " + content);
            }
        }
    }
}